package org.xawl.news.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.xawl.news.entity.user.User;
import org.xawl.news.util.SessionUtil;

public class PermissionFilter implements Filter {

	private Set<String> prefixIignores = new HashSet<String>();

	@Override
	public void init(FilterConfig config) throws ServletException {
		String cp = config.getServletContext().getContextPath();
		String ignoresParam = config.getInitParameter("ignores");
		String[] ignoreArray = ignoresParam.split(",");
		for (String s : ignoreArray) {
			prefixIignores.add(cp + s);
		}
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		if (canIgnore(request)) {
			chain.doFilter(req, res);
			return;
		}
		
		// servlet部分有效地址
		String uri = request.getServletPath();
		if("/login.jsp".equals(uri) || "/loginServlet".startsWith(uri)) {
			chain.doFilter(request, response);
			return;
		} 
		User user = (User)SessionUtil.getCurrentUser(request);
		if (user == null) {
			((HttpServletResponse) response).sendRedirect("login.jsp");
		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
		prefixIignores = null;
	}

	private boolean canIgnore(HttpServletRequest request) {
		String url = request.getRequestURI();
		for (String ignore : prefixIignores) {
			if (url.startsWith(ignore)) {
				return true;
			}
		}
		return false;
	}

}
